import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import os from 'os'

import {
  app,
  clipboard,
  Menu,
  getCurrentWebContents,
  getGlobal,
  BrowserWindow
} from '@electron/remote'

const api = {
  openDevTools: () => {
    getCurrentWebContents().openDevTools()
  },
  getGlobal,
  msgTrigger: (type: string, args, isSync?: boolean) => {
    if (isSync) {
      return electronAPI.ipcRenderer.sendSync('msg-trigger', { type, args })
    }

    return electronAPI.ipcRenderer.send('msg-trigger', { type, args })
  }
}

const electron = {
  ...electronAPI,
  app,
  clipboard,
  menu: Menu,
  BrowserWindow,
  os
}

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electron)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electron
  // @ts-ignore (define in dts)
  window.api = api
}
